package cn.meetingroom.service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CheckCode {
    private String code;
    private Random random = new Random();
    private String[] fontNames={"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"};  //验证码字体
    private String codeRange = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; //生成的验证码范围

    public BufferedImage getImage(){
        int width = 205;
        int height = 100;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(getColor(0,255));
        g.fillRect(0,0,width,height);

        //生成200条背景干扰线
        for (int i = 0; i < 200; i++) {
            g.setColor(getColor(0,255));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            g.drawLine(x,y,x+x1,y+y1);
        }

        //随机生成4个字符
        g.setColor(getColor(0,200));
        g.setFont(getFont());
        code = "";
        for (int i = 1; i <= 4; i++) {
            String str = getStr();
            code = code+str;
            g.drawString(str,width/5*i,height/2+10);
        }

        //生成100条前景干扰线
        g.setFont(new Font("Times New Roman",0,2));
        for (int i = 0; i < 100; i++) {
            g.setColor(getColor(100,255));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(10);
            int y1 = random.nextInt(10);
            g.drawLine(x,y,x1+x,y1+y);
        }

        return image;
    }

    //获取随机颜色
    private Color getColor(int min,int max){
        int a = (int)(Math.random()*(max-min+1)+min);
        int b = (int)(Math.random()*(max-min+1)+min);
        int c = (int)(Math.random()*(max-min+1)+min);
        return new Color(a,b,c);
    }

    //获取随机字符
    private String getStr(){
        int index = random.nextInt(codeRange.length());
        String str = codeRange.charAt(index)+"";
        return str;
    }

    //获取随机字体
    private Font getFont(){
        int index = random.nextInt(fontNames.length);
        String fontName = fontNames[index];
        int fontStyle = random.nextInt(4);
        int fontSize = random.nextInt(11)+40;
        return new Font(fontName,fontStyle,fontSize);
    }

    //获取验证码
    public String getCode() {
        return code;
    }

}
